package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/download.do")
public class FileDownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("456");
        System.out.println("123");
        doPost(request, response);
        System.out.println("789");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        response.getOutputStream():获取响应的字节输出流
//        request.getServletContext().getResourceAsStream()
//        response.setContentType();设置响应的内容类型
//        request.getServletContext().getMimeType() 获取MIME类型
        String path = request.getParameter("path");
        System.out.println(path);
        File file = new File("D:\\download\\" + path);
        if (!file.exists()) {
            response.getWriter().write("您要下载的内容不存在！");
            return;
        }
        path = new String(path.getBytes("UTF-8"),"ISO-8859-1");
        //设置响应头
        response.addHeader("content-disposition", "attachment;filename=" + path);
        //这里的IO操作可以封装到工具类
        FileInputStream fileInputStream = new FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();
        int length = 0;
        byte[] buffer = new byte[1024];
        while ((length = fileInputStream.read(buffer)) != -1) {
            outputStream.write(buffer);
            outputStream.flush();
        }
        outputStream.close();
        fileInputStream.close();
    }
}
